package com.mycompany.myapp.service.impl;

import com.mycompany.myapp.service.AddressService;
import com.mycompany.myapp.domain.Address;
import com.mycompany.myapp.repository.AddressRepository;
import com.mycompany.myapp.service.dto.AddressDTO;
import com.mycompany.myapp.service.mapper.AddressMapper;
import com.mycompany.myapp.web.rest.utils.ResultObj;
import com.mycompany.myapp.web.rest.utils.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing {@link Address}.
 */
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    private final Logger log = LoggerFactory.getLogger(AddressServiceImpl.class);

    private final AddressRepository addressRepository;

    private final AddressMapper addressMapper;

    public AddressServiceImpl(AddressRepository addressRepository, AddressMapper addressMapper) {
        this.addressRepository = addressRepository;
        this.addressMapper = addressMapper;
    }

    /**
     * Save a address.
     *
     * @param addressDTO the entity to save.
     * @return the persisted entity.
     */
    @Override
    public AddressDTO save(AddressDTO addressDTO) {
        log.debug("Request to save Address : {}", addressDTO);
        Address address = addressMapper.toEntity(addressDTO);
        address = addressRepository.save(address);
        return addressMapper.toDto(address);
    }

    /**
     * Get all the addresses.
     *
     * @return the list of entities.
     */
    @Override
    @Transactional(readOnly = true)
    public List<AddressDTO> findAll() {
        log.debug("Request to get all Addresses");
        return addressRepository.findAll().stream()
            .map(addressMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
    }


    /**
     * Get one address by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<AddressDTO> findOne(Long id) {
        log.debug("Request to get Address : {}", id);
        return addressRepository.findById(id)
            .map(addressMapper::toDto);
    }

    /**
     * Delete the address by id.
     *
     * @param id the id of the entity.
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete Address : {}", id);
        addressRepository.deleteById(id);
    }


    public Address findOneById(Long id) {
        return addressRepository.findOneById(id);
    }

    @Override
    public ResultObj getDefaultAddress(Long userId) {
        List<Address> list = findAllAddress(userId);
        if (!TypeUtils.isEmpty(list)) {
            for (Address ad : list) {
                if (ad.getIsDefault() == 1)
                    return ResultObj.backInfo(true, 200, "查找成功！", ad);
            }
            return ResultObj.backInfo(true, 200, "查找失败！", null);
        } else {
            return ResultObj.backInfo(true, 200, "地址为空！", null);
        }
    }

    public List<Address> findAllAddress(Long userId) {
        return addressRepository.findAddressBySuser_Id(userId);
    }

    @Override
    public ResultObj createAddress(AddressDTO addressDTO) {
        if (!TypeUtils.isEmpty(addressDTO)) {
            if (!TypeUtils.isEmpty(addressDTO.getSuserId())) {
                List<Address> addressList = findAllAddress(addressDTO.getSuserId());
                if (!TypeUtils.isEmpty(addressList)) {
                    addressDTO.setIsDefault(0);
                } else {
                    addressDTO.setIsDefault(1);
                }
                save(addressDTO);
                return ResultObj.backInfo(true, 200, "新增成功！", null);
            }
        }
        return ResultObj.backInfo(true, 200, "新增失败！", null);
    }

    @Override
    public ResultObj updateAddress(AddressDTO addressDTO) {
        Address address = findOneById(addressDTO.getId());
        if (!TypeUtils.isEmpty(address)) {
            save(addressDTO);
            return ResultObj.backInfo(true, 200, "修改成功", null);
        }
        return ResultObj.backInfo(false, 201, "修改失败", null);
    }

    @Override
    public ResultObj deleteAddress(Long userId, Long addressId) {
        Address address = addressRepository.findOneById(addressId);
        addressRepository.delete(address);
        if (address.getIsDefault() == 1) {
            List<Address> addressList = findAllAddress(userId);
            if (!TypeUtils.isEmpty(addressList)) {
                Address address2 = addressList.get(0);
                address2.setIsDefault(1);
                addressRepository.save(address2);
            }
        }
        return ResultObj.backInfo(true, 200, "删除成功", null);
    }

    @Override
    public ResultObj updateDefaultAddress(Long userId, Long AddressId) {

        Address address = addressRepository.getAddressByIsDefaultAndSuserId(1, userId);
        if (!TypeUtils.isEmpty(address)){
            address.setIsDefault(0);
            addressRepository.save(address);
            if (AddressId != 0) {
/*            Address address = addressRepository.getAddressBySuser_idAndIsDefault(userId,1);
            address.setIsDefault(0);
            addressRepository.save(address);*/
                Address a = addressRepository.findOneById(AddressId);
                a.setIsDefault(1);
                addressRepository.save(a);
                return ResultObj.backInfo(true, 200, "设置成功", null);
            }
        }

        return ResultObj.backInfo(true, 200, "清空成功", null);
    }
}
